package web

import (
	"encoding/base64"
	"encoding/json"
	"fmt"
	"html/template"
	"reflect"
)

var nb = base64.NewEncoding("NjCG7lX9WbVtnaA1TxzEY5OpuJ8Pr4oZF3s-SKdkchv2mqyLiD0efwRIBH_=6UgM").WithPadding('Q')

func NBase64(val interface{}) string {

	b, _ := json.Marshal(val)
	return nb.EncodeToString(b)
}

func DecBase64(pwd string) string {
	b, _ := nb.DecodeString(pwd)
	return string(b)
}

func EncBase64(pwd string) string {
	return nb.EncodeToString([]byte(pwd))
}

func Equals(a interface{}, b interface{}) bool {

	if a == nil && b == nil {
		return true
	}

	if a == nil || b == nil {
		return false
	}

	aa := reflect.ValueOf(a)
	bb := reflect.ValueOf(b)

	if aa.Kind() == reflect.Ptr {
		aa = aa.Elem()
	}

	if bb.Kind() == reflect.Ptr {
		bb = bb.Elem()
	}

	// if aa.Kind() != bb.Kind() {
	// 	return false
	// }

	//return aa.Interface() == bb.Interface()

	p := fmt.Sprintf("%v", aa.Interface())
	q := fmt.Sprintf("%v", bb.Interface())

	return p == q

}

func Sub(a interface{}, b interface{}) int {
	inta := a.(int)
	intb := b.(int)
	return inta - intb
}

var funcMap = template.FuncMap{
	"nbase64": NBase64,
	"equals":  Equals,
	"sub":     Sub,
}

func FuncMap() template.FuncMap {
	return funcMap
}
